﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.WebAPI.Application.Command.StartCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using System.Collections.Generic;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.StartCommandHandler
{
    /// <summary>
    /// 期初导出CommandHandler
    /// </summary>
    public class StartExportCommandHandler : IRequestHandler<StartExportCommand, IActionResult>
    {

        private readonly IStartService _startService;
        private readonly IMapper _mapper;

        public StartExportCommandHandler(IStartService startService, IMapper mapper)
        {
            _startService = startService;
            _mapper = mapper;
        }

        public async Task<IActionResult> Handle(StartExportCommand request, CancellationToken cancellationToken)
        {
           

            //获取数据列表
            var list =await _startService.GetStartList(request.Input);

            //获取数据
            var data = list.Data;

            //转换为导出类型
            var exportCustomerDto = _mapper.Map<List<StartOutput>, List<StartExcelOutPut>>(data);

            // 创建一个内存流对象
            MemoryStream ms = new MemoryStream();

            // 异步将导出的客户数据保存到内存流中
            await ms.SaveAsAsync(exportCustomerDto);

            // 将内存流的读取位置重置到开始位置
            ms.Seek(0, SeekOrigin.Begin);

            // 返回一个文件流结果，指定内容类型和文件下载名
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "期初信息.xlsx"
            };



        }

    }
}
